//
//  WebViewController.m
//  LiveDailyNews
//
//  Created by smu on 11-7-22.
//  Copyright 2011年 duk. All rights reserved.
//

#import "WebViewController.h"
#import "LiveDailyNewsAppDelegate.h"
#import "LiveDailyNews.h"
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>

@implementation WebViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
       
        
    }
    return self;
}

- (void)shareClick:(id)sender
{
    [self sendMail];
}

- (void)favoriteClick:(id)sender
{
    LiveDailyNewsAppDelegate *liveDailyNewsDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [liveDailyNewsDelegate managedObjectContext];
    NSError *error;
    LiveDailyNews *liveDailyNews = (LiveDailyNews *)[NSEntityDescription
                                                     insertNewObjectForEntityForName:@"LiveDailyNews" inManagedObjectContext:context];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if (favoriteFlag) {  //收藏状态 ，执行删除
       
        NSEntityDescription *entityDescription = [NSEntityDescription 
                                                  entityForName:@"LiveDailyNews"
                                                  inManagedObjectContext:context];
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        [request setEntity:entityDescription];
        
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"(title = %@)",[userDefaults objectForKey:@"title"]];
        [request setPredicate:pred];
        NSArray *objects = [context executeFetchRequest:request error:&error];
        
        for (NSManagedObject *delObject in objects) {
            [context deleteObject:delObject];
        }
        [request release];
        
        //删除图片
       
        NSFileManager *defaultManager = [NSFileManager defaultManager];
        
        BOOL boolRemove = [defaultManager removeItemAtPath:[[objects objectAtIndex:0] valueForKey:@"imagePath"] error:nil];
        if (!boolRemove) {
            NSLog(@"%@",[imageSavedPath description]);
            NSLog(@"remove cover image fail");
        }
        
        favoriteImage = [[UIImage alloc] initWithContentsOfFile:
                         [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"favorites_press.png"]];
        [favoriteButton setBackgroundImage:favoriteImage forState:UIControlStateNormal];
        
        favoriteFlag = NO;
        
    } else { //未收藏状态，执行添加
        //获取当前时间的时间戳   
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a=[dat timeIntervalSince1970]*1000;
        NSString *timeString = [NSString stringWithFormat:@"%i.png", a];    
        
        //网络图片存储到本地
        UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL: 
                                                        [NSURL URLWithString:[userDefaults objectForKey:@"imagePath"]]]];
        NSData *imageData = UIImagePNGRepresentation(image);
        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        NSString *documentsDirectory=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"favorite"]; 
        NSString *savedImagePath=[documentsDirectory stringByAppendingPathComponent:timeString];
        [imageData writeToFile:savedImagePath atomically:YES];
         NSLog(@"%@",savedImagePath );
        //把记录存进数据库
        liveDailyNews.title = [userDefaults objectForKey:@"title"];
        liveDailyNews.link = [userDefaults objectForKey:@"link"];
        liveDailyNews.content = [userDefaults objectForKey:@"content"];
        liveDailyNews.imagePath = savedImagePath;
        liveDailyNews.pubDate = [userDefaults objectForKey:@"pubDate"];
        liveDailyNews.category = [userDefaults objectForKey:@"category"];
        liveDailyNews.descrip = [userDefaults objectForKey:@"description"];
        if (![context save:&error]) {
            NSLog(@"Error %@",[error localizedDescription]);
        } else {
            favoriteImage = [[UIImage alloc] initWithContentsOfFile:
                             [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"right_flag.png"]];
            [favoriteButton setBackgroundImage:favoriteImage forState:UIControlStateNormal];
        }
        favoriteFlag = YES;

    }
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    //查询，判断当前记录是否收藏,标题判断
    LiveDailyNewsAppDelegate *liveDailyNewsDelegate = [[UIApplication sharedApplication] delegate];
    
    NSManagedObjectContext *context = [liveDailyNewsDelegate managedObjectContext];
    NSError *error;
    NSEntityDescription *entityDescription = [NSEntityDescription 
                                              entityForName:@"LiveDailyNews"
                                              inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"(title = %@)",[userDefaults objectForKey:@"title"]];
    [request setPredicate:pred];
    NSArray *objects = [context executeFetchRequest:request error:&error];

    
        if ([objects count] > 0) {  // 收藏
            //此段可在修改为使用当前数据库的数据
            favoriteImage = [[UIImage alloc] initWithContentsOfFile:
                             [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"right_flag.png"]];
            favoriteFlag = YES;
            
            
            
        } else { //未收藏
            favoriteImage = [[UIImage alloc] initWithContentsOfFile:
                             [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"favorites_press.png"]];
            favoriteFlag = NO;
        
        }
   

    [request release];
    
    UIImage *shareImage = [[UIImage alloc] initWithContentsOfFile:
                           [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"tasklist_bt0.png"]];
    
    
    
    UIButton *shareButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 32)];
    [shareButton setBackgroundImage:shareImage forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(shareClick:) forControlEvents:UIControlEventTouchUpInside];
    
    favoriteButton = [[UIButton alloc] initWithFrame:CGRectMake(55, 0, 50, 32)];
    [favoriteButton setBackgroundImage:favoriteImage forState:UIControlStateNormal];
    [favoriteButton addTarget:self action:@selector(favoriteClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *rightView = [[UIView alloc]  initWithFrame:CGRectMake(0, 0, 120, 35)];
    [rightView addSubview:shareButton];
    [rightView addSubview:favoriteButton];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
    
    favoriteImage = nil;
    
    
    UIView *contentView = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
	
	contentView.autoresizesSubviews = YES;
	self.view = contentView;
	[self.view setBackgroundColor:[UIColor clearColor]];
//    实现UIWebView
    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, contentView.bounds.size.width, contentView.bounds.size.height - 44)];
    [webView setUserInteractionEnabled:YES]; //是否支持交互
    [webView setDelegate:self];//委托
    [webView setOpaque:NO];  //透明
    [self.view addSubview:webView];  //加载到自己的view
    
    
    //取得数据
   
//    NSURL *link = [[NSURL alloc] initWithString:[userDefaults objectForKey:@"link"]];

   // [webView loadRequest:[NSURLRequest requestWithURL:link]];//笔者习惯采用loadRequest方式，你可以采用其他方式
    NSMutableString *htmlString = [[NSMutableString alloc] init];
    [htmlString setString:@"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><title>无标题文档</title></head><body><span style=\"font-size: 24px\"><strong style=\"color: #0099CC;font-weight: bold;\" >"];
    [htmlString appendString:[userDefaults objectForKey:@"title"]];
    [htmlString appendString:@"</strong></span><br/><br/>"];
    [htmlString appendString:[userDefaults objectForKey:@"pubDate"]];
    [htmlString appendString:[userDefaults objectForKey:@"category"]];
    [htmlString appendString:@"<br/><img height=\"180\" width=\"250\" src=\""];
    [htmlString appendString:[userDefaults objectForKey:@"imagePath"]];
    [htmlString appendString:@"\" width=\"304\" /><br/>"];
    [htmlString appendString:[userDefaults objectForKey:@"content"]];
    [htmlString appendString:@"</body></html>"];
    
    NSBundle *bundle = [NSBundle mainBundle];
    
    
    [webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:[bundle bundlePath]]];
    [webView setBackgroundColor:[UIColor whiteColor]];

    

    
    
    
    
    NSLog(@"%@",[userDefaults objectForKey:@"imagePath"]);
    [super viewDidLoad];
//    [context release];
    
    
    // Do any additional setup after loading the view from its nib.
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//    opaqueview.hidden = YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
//    opaqueview.hidden = NO;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



///////////////////////分享链接
//邮件发送功能是由MessageUI Framework提供的，
//这个框架是iPhone sdk中最简单的框。由一个类、一个视图控制器，一个protocol组成
-(void)sendMail
{
    //    创建视图控制器：
    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
    mc.mailComposeDelegate = self;
    //    创建视图控制器：
    [mc setSubject:@"欢迎访问生活新报"];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *content=[[NSString alloc] initWithFormat:@"您好:欢迎访问生活新报，这是我们的网址：%@",
                       [userDefaults objectForKey:@"link"]];
    
    [mc setMessageBody:content isHTML:NO];
    
    //视图呈现
    [self presentModalViewController:mc animated:YES]; 
    [mc release];
	
}

//视图控制器的委托方法
//邮件视图控制器的委托方法包含在MFMailComposeViewControllerDelegate中，无论用户是否发送或取消发送，不论系统是否能够发送邮件，
// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{	
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MFMailComposeResultCancelled:
			break;
		case MFMailComposeResultSaved:
			break;
		case MFMailComposeResultSent:
			break;
		case MFMailComposeResultFailed:
			break;
		default:
			break;
	}
	[self dismissModalViewControllerAnimated:YES];
}

@end
